package ru.compscicenter.databases.zaikina.nodes;

import ru.compscicenter.databases.zaikina.common.AbstractManagedObject;
import ru.compscicenter.databases.zaikina.common.ManagedObject;
import ru.compscicenter.databases.zaikina.common.Vocabulary;
import ru.compscicenter.databases.zaikina.common.commands.*;
import ru.compscicenter.databases.zaikina.common.model.WordWithReferences;

import java.util.ArrayList;

public class VocabularyNode extends AbstractManagedObject {
    private Vocabulary vocabulary;// = new Vocabulary();
    private Integer nodeId;

    public VocabularyNode(Integer id) {
        vocabulary = new Vocabulary(id);
        vocabulary.load();
        nodeId = id;
    }

    public SysCommand<?, ?> process(StringListCommand command) {
        if (command.getType().equals(SysCommandType.GetSameWords)) {
            return new WordsCommand(SysCommandType.WordsAnswer, vocabulary.get(command.getBody()));
        }
        if (command.getType().equals(SysCommandType.GetWordsWithReferences)) {
            ArrayList<WordWithReferences> words = new ArrayList<WordWithReferences>();
            for (String str : command.getBody()) {
                words.addAll(vocabulary.get(str));
            }
            return new FullWordsCommand(SysCommandType.FullWordsAnswer, words, -1);
        }
        return null;
    }

    public EmptyCommand process(FullWordsCommand command) {
        System.out.println("Vocabulary node. Process started " + command.getType());
        if (command.getType().equals(SysCommandType.AddWords)) {
            System.out.println("Added words....\r\n" + command.toJSONString());
            vocabulary.add(command.getBody());
            return new EmptyCommand(SysCommandType.Success);
        }
        if (command.getType().equals(SysCommandType.RemoveWords)) {
            vocabulary.remove(command.getBody());
            return new EmptyCommand(SysCommandType.Success);
        }
        if (command.getType().equals(SysCommandType.UpdateWords)) {
            vocabulary.update(command.getBody());
            return new EmptyCommand(SysCommandType.Success);
        }

        return null;
    }

    public Vocabulary getVocabulary() {
        return vocabulary;
    }

    public VocabularyNode clone() {
        VocabularyNode copy = new VocabularyNode(nodeId);
        copy.vocabulary = vocabulary.clone();
        return copy;
    }

    public void commit() {
        vocabulary.commit();
    }

    public Integer getNodeId() {
        return nodeId;
    }
}
